<template>
  <el-dialog v-model="openDialog" :title="dialogTitle" :width="800" :before-close="handleClose">
    <div class="new-dialogDiv">
      <!--计算结果展示窗口-->
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="统计图" name="first">
          <!--          <div id="resultChartDiv" style="width:100%;height:400px;"></div>-->
          <div ref="resultChartDiv" style="width:100%;height:400px;"></div>
        </el-tab-pane>
        <el-tab-pane label="表格" name="second">
          <el-table v-loading="loading" ref="tableRef" :data="dataList" stripe row-key="versionCode">
            <el-table-column v-if="props.result.resultDialogType == '与地层岩性的关系'" :label="valueTypeLabel" align="center"
              prop="name" />
            <el-table-column v-else :label="valueTypeLabel" align="center" prop="valueType" />
            <el-table-column label="滑坡面积（km²）" align="center" prop="slopeArea" />
            <el-table-column label="滑坡面密度（%）" align="center" prop="slopeDensity" />
          </el-table>
          <div style="text-align: center;margin-top: 15px;">
            <el-button type="primary" @click="handleExport">导出</el-button>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </el-dialog>
</template>

<script setup>
import * as echarts from "echarts";
import { exportByDspIdAndType } from "@/api/slideAssess/distributionPatternAnalysis/indexMap";
import { export_json_to_excel } from '@/utils/Export2Excel';
// import { export_json_to_excel } from '@/utils/test';

const { proxy } = getCurrentInstance();
const props = defineProps(['open', 'result']);
const emits = defineEmits(['closeResultDialog'])
const loading = ref(false);

//是否显示计算结果弹窗
const openDialog = ref(false);
//计算结果弹窗标题
const dialogTitle = ref("");
//计算结果弹窗tab选择
const activeName = ref('first');
//计算结果数据列表
const dataList = ref([]);
//计算结果分段名称
const valueTypeLabel = ref("");
//计算结果图例列表
const legendList = ref([]);
//统计图
const resultChart = ref(null);

//是否显示
const isOpen = watch(() => props.open, value => {// watch函数监听props.open
  openDialog.value = value;
}, { immediate: true });

const handleClose = () => {
  openDialog.value = false;
  emits('closeResultDialog', true);
}

const handleClick = (tab, event) => {
  console.log(tab, event)
}

//获取计算结果分段名称
function getValueTypeLabel(value) {
  dialogTitle.value = value + "统计结果";
  let label = "";
  if (value == "与地震烈度的关系") {
    label = "地震烈度";
  } else if (value == "与距断层距离的关系") {
    label = "距断层距离（km）";
  } else if (value == "与高程的关系") {
    label = "海拔高程（km）";
  } else if (value == "与地形坡度的关系") {
    label = "地形坡度（°）";
  } else if (value == "与坡向的关系") {
    label = "坡向";
  } else if (value == "与水系的关系") {
    label = "距水系距离（m）";
  } else if (value == "与地层岩性的关系") {
    label = "地层岩性";
  }
  valueTypeLabel.value = label;
}

//获取计算结果表格数据列表
function getResultDataList(type, resultDataList, resultLegendList) {
  console.log("获取计算结果表格数据列表");
  console.log(type);
  console.log(resultDataList);
  console.log(resultLegendList);
  if (type && resultDataList && resultLegendList) {
    let list = [];
    //设置默认值为0
    for (let i = 0; i < resultLegendList.length; i++) {
      //分段名称
      let valueType = resultLegendList[i].name;
      let slopeArea = 0;
      let slopeDensity = 0;
      let tempObj = {
        valueType: valueType,
        slopeArea: slopeArea,
        slopeDensity: slopeDensity
      }
      list.push(tempObj);
    }
    console.log(resultDataList.length);
    for (let i = 0; i < resultDataList.length; i++) {
      let obj = resultDataList[i];
      let slopeArea = obj.slopeArea;
      let slopeDensity = obj.slopeDensity;
      //获取分段名称
      let valueType = "";
      let val = "";
      if (type == "与地震烈度的关系") {
        val = obj.intensity;//烈度。5Ⅴ、6 Ⅵ、7 Ⅶ、8 Ⅷ、9 Ⅸ、10 Ⅹ、11 Ⅺ、12 Ⅻ
      } else if (type == "与距断层距离的关系") {
        val = obj.faultRange;//距断层的距离。7,>30;6,25~30;5,20~25;4,15~20;3,10~15;2,5~10;1,0~5
      } else if (type == "与高程的关系") {
        val = obj.teraRange;//高程。1,<0.6;2,0.6~1;3,1~1.5;4,1.5~2;5,2~2.5;6,2.5~3;7,3~3.5;8,>3.5
      } else if (type == "与地形坡度的关系") {
        val = obj.slopeRange;//坡度。1,<15;2,15~25;3,25~35;4,35~45;5,45~55;6,>55
      } else if (type == "与坡向的关系") {
        val = obj.aspectRange;//坡向1,N;2,NE;3,E;4,ES;5,S;6,SW;7,W;8,WN
      } else if (type == "与水系的关系") {
        val = obj.drainageRange;//距水系距离。1,0~500;2,500~1000;3,1000~1500;4,1500~2000;5,>2000
      } else if (type == "与地层岩性的关系") {
        val = obj.lithologyRange;//地层岩性。1,Q4;2,Er;3,T3z;4,T3zh;5,T2zg;6,T1b;7,Tγo;8,P2b-d;9,Psd-d;10,C2h;11,Cz-h;12,D2y
      }
      if (val && resultLegendList && resultLegendList.length > 0) {
        for (let i = 0; i < resultLegendList.length; i++) {
          if (resultLegendList[i].value == val) {
            let name = resultLegendList[i].name;
            valueType = resultLegendList[i].name;//分段名称
            if (type == "与地层岩性的关系") {
              valueType = resultLegendList[i].value;//地层岩性符号
            }
            let tempObj = {
              name: name,
              valueType: valueType,
              slopeArea: slopeArea,
              slopeDensity: slopeDensity
            }
            list[i] = tempObj;
            break;
          }
        }
      }
    }
    dataList.value = list;
    console.log("计算结果数据列表表格");
    console.log(list);
  }
}

//表格导出Excel
function handleExport() {
  // let dspId = props.result.dspId;
  // let type = props.result.type;//1-7
  // proxy.download("/lawAnalysis/exportByDspIdAndType", {
  //   dspId:dspId,type:type
  // }, `表格_${new Date().getTime()}.xlsx`);

  /*exportByDspIdAndType(dspId,type).then(response => {
    console.log("表格导出Excel");
    console.log(response);
  }).catch(() => {
    // proxy.$modal.msgError("导出失败");
  });*/


  if (dataList.value && dataList.value.length) {
    // 设置导出数据格式并导出
    const arrData = [];
    dataList.value.map(item => {
      if(props.result.resultDialogType=='与地层岩性的关系') {
        arrData.push([item.valueTypeLabel, item.slopeArea, item.slopeDensity]);
      }else{
        arrData.push([item.valueType, item.slopeArea, item.slopeDensity]);
      }
    });

    export_json_to_excel({
    	// 表头
    	header: [valueTypeLabel.value, '滑坡面积（km²）', '滑坡面密度（%）'],
    	data: arrData,
    	filename: '表格', //文件名
    	autoWidth: true,
    	bookType: 'xlsx',
    });
  } else {
    proxy.$modal.msgWarning('没矩阵数据，无法导出！');
  }
}

//获取统计图
function getResultChart() {
  let xAxisLabel = valueTypeLabel.value;//X轴名称
  let list = dataList.value;//计算结果数据列表表格
  const resultChartDiv = proxy.$refs.resultChartDiv;
  // if(list!=null && list.length>0 && document.getElementById('resultChartDiv')) {
  if (list != null && list.length > 0) {
    if (resultChart.value) {
      resultChart.value.dispose();//移除
    }
    //初始化
    // resultChart.value = echarts.init(document.getElementById('resultChartDiv'));
    resultChart.value = echarts.init(resultChartDiv);

    //分段名称数组
    let xDataArray = [];
    for (let i = 0; i < list.length; i++) {
      xDataArray.push(list[i].valueType);
    }

    //滑坡面密度（%）数组
    let yDataArray1 = [];
    for (let i = 0; i < list.length; i++) {
      yDataArray1.push(list[i].slopeDensity);
    }

    //滑坡面积（km²）数组
    let yDataArray2 = [];
    for (let i = 0; i < list.length; i++) {
      yDataArray2.push(list[i].slopeArea);
    }

    // 指定图表的配置项和数据
    let option = {
      // color: ['rgba(50, 229, 255, 1)', 'rgba(250, 207, 18, 1)'],
      color: ['rgb(33, 158, 188)', 'rgb(254, 183, 5)'],
      tooltip: {
        axisPointer: {
          type: "line", // 指示器类型（'line' 直线指示器；'shadow' 阴影指示器；'none' 无指示器；'cross' 十字准星指示器。）
          snap: false, // 坐标轴指示器是否自动吸附到点上。默认自动判断。
        },
        /*axisPointer: {
          type: 'cross',
          crossStyle: {
            color: '#999'
          }
        },*/
        formatter: function (params) {
          if (params.dataIndex >= 0) {
            // console.log(params);
            let tip = xAxisLabel + "：" + xDataArray[params.dataIndex] + "<br/>";
            if (xAxisLabel == "地层岩性") {
              tip = xAxisLabel + "符号：" + xDataArray[params.dataIndex] + "<br/>";
              tip += xAxisLabel + "名称：" + list[params.dataIndex].name + "<br/>";
            }
            tip += "滑坡面密度（%）：" + yDataArray1[params.dataIndex] + "<br/>";
            tip += "滑坡面积（km²）：" + yDataArray2[params.dataIndex];
            return tip;
          }
        }
      },
      legend: {
        top: '5%',
        left: 'center',
        data: ['滑坡面密度（%）', '滑坡面积（km²）']
      },
      grid: {
        top: '20%',
        left: '10%',
        right: '10%',
        bottom: '0%',
        containLabel: true
      },
      toolbox: {
        feature: {
          saveAsImage: {}
        }
      },
      xAxis: [
        {
          type: 'category',
          data: xDataArray,
          axisLine: {
            show: true,
            lineStyle: {
              color: 'rgb(2,48,74)'
            }
          },
          splitLine: {
            show: false,
            lineStyle: {
              color: 'blue',
              width: 1,
              type: 'dashed'
            }
          },
          axisPointer: {
            type: 'shadow'
          },
        }, {
          position: 'bottom',
          data: [xAxisLabel],
          axisLabel: {
            margin: 30,
            interval: 0,
            rich: {
              offset: {
                width: 40
              }
            }
          }
        }
      ],
      yAxis: [
        {
          type: 'value',
          name: `                {legend|}  {value|滑坡面密度（%）}`,
          axisLabel: {
            color: 'rgb(254,183,5)'
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#FFDEAD'
            }
          },
          splitLine: {
            show: false,
            lineStyle: {
              color: 'blue',
              width: 1,
              type: 'dashed'
            }
          },
          nameTextStyle: {
            rich: {
              legend: {
                width: 12,
                height: 4,
                backgroundColor: 'rgb(254,183,5)'
              },
              value: {
                color: 'black'
              }
            }
          }
        },
        {
          type: 'value',
          name: `{legend|}  {value|滑坡面积（km²）}           `,
          axisLabel: {
            color: 'rgb(33,158,188)'
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#66CDAA'
            }
          },
          splitLine: {
            lineStyle: {
              color: '#E6E6FA',
              width: 1,
              type: 'solid'
            }
          },
          nameTextStyle: {
            rich: {
              legend: {
                width: 12,
                height: 4,
                backgroundColor: 'rgb(33,158,188)'
              },
              value: {
                color: 'black'
              }
            }
          }
        }
      ],
      series: [
        {
          name: '滑坡面密度（%）',
          type: 'line',
          data: yDataArray1,
          itemStyle: {
            // color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
            //   {
            //     offset: 0,
            //     color: 'rgba(183, 75, 238)'
            //   },
            //   {
            //     offset: 1,
            //     color: 'rgba(250, 207, 18)'
            //   }
            // ])
            color:'rgb(254, 183, 5)'
          },
          /*areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
              {
                offset: 0,
                color: 'rgba(183, 75, 238,0.2)'
              },
              {
                offset: 1,
                color: 'rgba(250, 207, 18)'
              }
            ])
          },*/
          // showSymbol: false
        },
        {
          name: '滑坡面积（km²）',
          type: 'bar',
          yAxisIndex: 1,
          data: yDataArray2,
          barWidth: 14, // 柱状图的宽度
          itemStyle: {
            borderRadius: 8,
            // color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
            //   { offset: 0, color: 'rgba(50, 229, 255, 1)' },
            //   { offset: 1, color: 'rgba(50, 229, 255, 0.8)' }
            // ])
            color:'rgb(33, 158, 188)'
          }
        }
      ]
    };

    // 使用刚指定的配置项和数据显示图表。 给一个延时
    resultChart.value.clear();
    option && resultChart.value.setOption(option);
  }
}

//雷达图
function getResultChart2() {
  let xAxisLabel = valueTypeLabel.value;//X轴名称
  let list = dataList.value;//计算结果数据列表表格
  const resultChartDiv = proxy.$refs.resultChartDiv;
  // if(list!=null && list.length>0 && document.getElementById('resultChartDiv')) {
  if (list != null && list.length > 0) {
    if (resultChart.value) {
      resultChart.value.dispose();//移除
    }
    //初始化
    // resultChart.value = echarts.init(document.getElementById('resultChartDiv'));
    resultChart.value = echarts.init(resultChartDiv);

    //分段名称数组
    let xDataArray = [];
    for (let i = 0; i < list.length; i++) {
      xDataArray.push(list[i].valueType);
    }

    //滑坡面密度（%）数组
    let yDataArray1 = [];
    for (let i = 0; i < list.length; i++) {
      yDataArray1.push(list[i].slopeDensity);
    }

    //滑坡面积（km²）数组
    let yDataArray2 = [];
    for (let i = 0; i < list.length; i++) {
      yDataArray2.push(list[i].slopeArea);
    }

    /*//test
    let dataArr1 = [];
    let dataArr2 = [];
    for(let i=0;i<8;i++){
      let slopeArea = Math.random()*100;
      let slopeDensity = Math.random();
      dataArr1.push(slopeArea);
      dataArr2.push(slopeDensity);
    }
    yDataArray1 = dataArr1;
    yDataArray2 = dataArr2;*/

    //坡向1,N;2,NE;3,E;4,ES;5,S;6,SW;7,W;8,WN
    //转换数组
    // 各个维度的最大值
    // let nameArr = ['北','北西','西','南西','南','南东','东','北东'];
    let nameArr = ['N', 'NW', 'W', 'SW', 'S', 'SE', 'E', 'NE'];
    let dataArr1 = [];
    let dataArr2 = [];
    let dataMax1 = [];
    let dataMax2 = [];
    for (let i = 0; i < nameArr.length; i++) {
      let index = 0;
      if (i > 0) {
        index = nameArr.length - i;
      }
      let obj1 = {
        name: nameArr[i],
        max: 1
      }
      dataMax1.push(obj1);
      dataArr1.push(yDataArray1[index]);
      let obj2 = {
        name: nameArr[i],
        max: 100
      }
      dataMax2.push(obj2);
      dataArr2.push(yDataArray2[index]);
    }
    console.log("雷达图数据");
    console.log(nameArr);
    console.log(dataArr1);
    console.log(dataArr2);
    // 指定图表的配置项和数据
    let option = {
      tooltip: {
        /*formatter: function (params){
          console.log("formatter");
          console.log(params);
        }*/
        position: function (point, params, dom, rect, size) {//设置提示框位置，防止超出范围不显示
          let x = 0; // x坐标位置
          let y = 0; // y坐标位置
          // 当前鼠标位置
          let pointX = point[0];
          let pointY = point[1];
          // 外层div大小
          // let viewWidth = size.viewSize[0];
          // let viewHeight = size.viewSize[1];
          // 提示框大小
          let boxWidth = size.contentSize[0];
          let boxHeight = size.contentSize[1];
          // boxWidth > pointX 说明鼠标左边放不下提示框
          if (boxWidth > pointX) {
            x = 5;
          } else { // 左边放的下
            x = pointX - boxWidth;
          }
          // boxHeight > pointY 说明鼠标上边放不下提示框
          if (boxHeight > pointY) {
            y = 5;
          } else { // 上边放得下
            y = pointY - boxHeight;
          }
          return [x, y];
        },
      },
      legend: {
        left: 'center',
        data: ['滑坡面密度（%）', '滑坡面积（km²）']
      },
      radar: [{
        indicator: dataMax1,  //配置各个维度的最大值
        axisLabel: {
          show: true,
          color: '#333',
          showMinLabel: false
        },
        center: ['25%', '50%'],
        radius: 150
      }, {
        indicator: dataMax2,  //配置各个维度的最大值
        axisLabel: {
          show: true,
          color: '#333',
          showMinLabel: false
        },
        center: ['75%', '50%'],
        radius: 150
      }],
      series: [
        {
          type: 'radar',
          radarIndex: 0,
          data: [
            {
              name: '滑坡面密度（%）',
              value: dataArr1
            }
          ]
        },
        {
          type: 'radar',
          radarIndex: 1,
          data: [
            {
              name: '滑坡面积（km²）',
              value: dataArr2
            }
          ]
        }
      ]
    };

    // 使用刚指定的配置项和数据显示图表。 给一个延时
    resultChart.value.clear();
    option && resultChart.value.setOption(option);
  }
}

//获取计算结果
const getResult = watch(() => props.result, value => {// watch函数监听props.result
  if (value) {
    let resultDialogType = value.resultDialogType;
    if (resultDialogType) {
      //获取计算结果分段名称
      getValueTypeLabel(resultDialogType);
      let resultLegendList = value.resultLegendList;//计算结果图例列表
      if (resultLegendList) {
        legendList.value = resultLegendList;
        let resultDataList = value.resultDataList;//计算结果数据列表
        if (resultDataList) {
          //获取计算结果表格数据列表
          getResultDataList(resultDialogType, resultDataList, resultLegendList);
          nextTick(() => {
            if (resultDialogType == "与坡向的关系") {
              //获取雷达图
              getResultChart2();
            } else {
              //获取统计图
              getResultChart();
            }
          });
          /*setTimeout(function(){
            if(resultDialogType=="与坡向的关系"){
              //获取雷达图
              getResultChart2();
            }else{
              //获取统计图
              getResultChart();
            }
          },300);*/
        }
      }
    }
  }

}, { immediate: true });

onMounted(() => {
  //获取统计图
  // getResultChart();
})
</script>

<style scoped lang="scss">
.new-dialogDiv {
  padding: 20px;
}
</style>